package cn.service.impl;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.List;

import net.sf.json.JSONObject;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.dao.ApiMapper;
import cn.dao.ApipraMapper;
import cn.dao.LogMapper;
import cn.dao.UserMapper;
import cn.domain.Api;
import cn.domain.ApiExample;
import cn.domain.Apipra;
import cn.domain.Log;
import cn.domain.User;
import cn.entity.Apis;
import cn.service.ApiService;

@Service
@Transactional(rollbackFor=Exception.class)
public class ApiServiceImpl implements ApiService {

	@Autowired
	private ApiMapper apiMapper;
	@Autowired
	private ApipraMapper apipraMapper;
	@Autowired
	private LogMapper logMapper;
	@Autowired
	private UserMapper userMapper;

	@Override
	public void insert(Apis  apis) {
		Api api = new Api();
		try {
			BeanUtils.copyProperties(api, apis);
			api.setUpdatetime(new Date());
			apiMapper.insert(api);
			if(api.getId()<=0){
				ApiExample example = new ApiExample();
				example.createCriteria().andAidEqualTo(api.getAid()).andCnameEqualTo(api.getCname()).andApiuserEqualTo(api.getApiuser());
				List<Api> list = apiMapper.selectByExample(example);
				if(list!=null && list.size()>0){
					api = list.get(0);
				}
			}
			
			for(Apipra ap:apis.getApipras()){
				ap.setApiid(api.getId());
				apipraMapper.insert(ap);
			}
			Log log = new Log();
			log.setInserttime(new Date());
			log.setUid(apis.getApiuser());
			log.setTitle("接口");
			log.setBody("创建接口文档成功！");
			log.setApiid(api.getId());
			logMapper.insert(log);
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void delete(String deleteId) {
		for(String id:deleteId.split(",")){
			Api api = apiMapper.selectByPrimaryKey(Integer.parseInt(id));
			api.setIsdel(1);
			api.setUpdatetime(new Date());
			apiMapper.updateByPrimaryKey(api);
		}
	}

	@Override
	public boolean getOne(Apis apis) {
		ApiExample example = new ApiExample();
		example.createCriteria().andCnameEqualTo(apis.getCname()).andIsdelEqualTo(0)
		.andAidEqualTo(apis.getAid());
		List<Api> apisdb = apiMapper.selectByExample(example);
		if(!apisdb.isEmpty() && apisdb.size() > 0){
			return true;
		}
		return false;
	}


	@Override
	public Api selectOne(String deleteId) {
		return apiMapper.selectByPrimaryKey(Integer.parseInt(deleteId));
	}


	@Override
	public void update(Api Api) {
		apiMapper.updateByPrimaryKey(Api);
	}


	@Override
	public List<Api> getAll(Api api) {
		return apiMapper.getAll(api);
	}

	@Override
	public void update(Apis apis, Api api_db, List<Apipra> apipras_db) {
		Api api = new Api();
		try {
			BeanUtils.copyProperties(api, apis);
			api.setUpdatetime(new Date());
			apiMapper.updateByPrimaryKey(api);
			for(Apipra i:apipras_db){
				apipraMapper.deleteByPrimaryKey(i.getId());
			}
			for(Apipra ap:apis.getApipras()){
				ap.setApiid(api.getId());
				apipraMapper.insert(ap);
			}
			Log log = new Log();
			log.setInserttime(new Date());
			log.setUid(apis.getApiuser());
			log.setTitle("接口");
			StringBuffer sb = new StringBuffer();
			StringBuffer sb1 = new StringBuffer();
			if(!api.getCname().equals(api_db.getCname())){
				sb.append("接口名称【"+api_db.getCname()+"】变更为【"+api.getCname()+"】");
				sb.append("<br>");
			}
			if(!api.getCdesc().equals(api_db.getCdesc()) && !"".equals(api.getCdesc())){
				sb.append("接口描述【"+api_db.getCdesc()+"】变更为【"+api.getCdesc()+"】");
				sb.append("<br>");
			}
			if(api.getDevuser().intValue() != api_db.getDevuser().intValue()){
				User u = userMapper.selectByPrimaryKey(api.getDevuser());
				User db_u = userMapper.selectByPrimaryKey(api_db.getDevuser());
				sb.append("开发人员【"+db_u.getNiceName()+"】变更为【"+u.getNiceName()+"】");
				sb.append("<br>");
			}
			if(!api.getType().equals(api_db.getType())){
				sb.append("接口类型【"+api_db.getType()+"】变更为【"+api.getType()+"】");
				sb.append("<br>");
			}
			if(!api.getUrl().equals(api_db.getUrl())){
				sb.append("接口请求URL【"+api_db.getUrl()+"】变更为【"+api.getUrl()+"】");
				sb.append("<br>");
			}
			if(!api.getIsok().equals(api_db.getIsok())){
				String des_api = getIsOkDes(api.getIsok());
				String des_api_db = getIsOkDes(api_db.getIsok());
				sb.append("接口状态【"+des_api_db+"】变更为【"+des_api+"】");
				sb.append("<br>");
			}
			if(apipras_db.size() == apis.getApipras().size()){
				String des_apipras = getReqPraDes(apipras_db,apis.getApipras());
				if(!"".equals(des_apipras)){
					sb.append("请求参数列表");
					sb.append("<br>");
					sb.append(des_apipras);
					sb.append("<br>");
				}
			}else{
				String des_apipras_db = getReqPraDes(apipras_db);
				String des_apipras = getReqPraDes(apis.getApipras());
				sb.append("请求参数列表【"+des_apipras_db+"】变更为【"+des_apipras+"】");
				sb.append("<br>");
			}
			if(!api.getCallbak().equals(api_db.getCallbak())){
				sb.append("响应参数列表【"+api_db.getCallbak()+"】变更为【"+api.getCallbak()+"】");
				sb.append("<br>");
			}
			if(!"".equals(sb.toString())){
				sb1.append("编辑接口文档");
				sb1.append(sb);
				sb1.append("<br>");
				log.setBody(sb1.toString());
				log.setApiid(api.getId());
				logMapper.insert(log);
			}
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
	}
	
	private String getIsOkDes(String isOk){
		if("ok".equals(isOk)){
			return "接口文档撰写完成";
		}else if("no".equals(isOk)){
			return "接口文档撰写没完成";
		}else if("dev".equals(isOk)){
			return "接口开发阶段";
		}else if("over".equals(isOk)){
			return "接口开发完成";
		}else if("testno".equals(isOk)){
			return "接口开发完成没有自测";
		}else if("testok".equals(isOk)){
			return "接口开发完成已经自测完成";
		}
		return "";
	}

	private String getReqPraDes(List<Apipra> apipras){
		StringBuffer sb = new StringBuffer();
		for(int j=0;j<apipras.size();j++){
			Apipra i = apipras.get(j); 
			sb.append("{名称:"+i.getCname()+",描述:"+i.getCdesc()+",类型:"+i.getType()+",备注:"+i.getCbak()+"}");
			if(j<apipras.size()-1){
				sb.append(",");
				sb.append("<br>");
			}
		}
		return sb.toString();
	}
	
	private String getReqPraDes(List<Apipra> apipras_db,List<Apipra> apipras){
		StringBuffer sb = new StringBuffer();
		StringBuffer sb1 = new StringBuffer();
		for(int j=0;j<apipras.size();j++){
			Apipra i_db = apipras_db.get(j); 
			Apipra i = apipras.get(j); 
			int index = 0;
			if(!i_db.getCname().equals(i.getCname())){
				sb.append("名称【"+i_db.getCname()+"】变更为【"+i.getCname()+"】");
				index++;
			}
			if(!i_db.getCdesc().equals(i.getCdesc())){
				sb.append("描述【"+i_db.getCdesc()+"】变更为【"+i.getCdesc()+"】");
				index++;
			}
			if(!i_db.getType().equals(i.getType())){
				sb.append("类型【"+i_db.getType()+"】变更为【"+i.getType()+"】");
				index++;
			}
			if(!i_db.getCbak().equals(i.getCbak())){
				sb.append("备注【"+i_db.getCbak()+"】变更为【"+i.getCbak()+"】");
				index++;
			}
			if(j<apipras.size()-1){
				if(!"".equals(sb.toString())){
					sb1.append("{");
					sb1.append(sb);
					sb1.append("}");
					if(index >= 2){
						sb1.append(",");
					}
					sb1.append("<br>");
				}
			}
		}
		return sb1.toString();
	}

	@Override
	public void updateStatus(Api api_db) {
		api_db.setUpdatetime(new Date());
		apiMapper.updateByPrimaryKey(api_db);
		Log log = new Log();
		log.setInserttime(new Date());
		log.setUid(api_db.getApiuser());
		log.setTitle("接口");
		log.setBody("修改接口状态为:"+getIsOkDes(api_db.getIsok()));
		log.setApiid(api_db.getId());
		logMapper.insert(log);
	}
	
	@Override
	public String debugInterface(String url,Integer uid,Integer apiid,String apiname){
		StringBuffer sbResult = new StringBuffer();
		try{
			URL getUrl = new URL(url);
	        // 根据拼凑的URL，打开连接，URL.openConnection函数会根据URL的类型，
	        // 返回不同的URLConnection子类的对象，这里URL是一个http，因此实际返回的是HttpURLConnection
	        HttpURLConnection connection = (HttpURLConnection) getUrl
	                .openConnection();
	        // 进行连接，但是实际上get request要在下一句的connection.getInputStream()函数中才会真正发到
	        // 服务器
	        connection.connect();
	        
	        // 取得输入流，并使用Reader读取
	        BufferedReader reader = new BufferedReader(new InputStreamReader(
	                connection.getInputStream(),"UTF-8"));
	        String lines;
	        
	        while ((lines = reader.readLine()) != null) {
	        	sbResult.append(lines);
	        }
	        reader.close();
	        // 断开连接
	        connection.disconnect();
		}catch(Exception e){
			sbResult.append("error");
		}		
		Log log = new Log();
		log.setInserttime(new Date());
		log.setUid(uid);
		log.setApiid(apiid);
		log.setTitle("接口");
		log.setBody("测试接口"+"【"+apiname+"】</br>"+"接口请求URL【"+url+"】</br>测试结果【"+sbResult+"】");
		logMapper.insert(log);
        return sbResult.toString();
	}

	/* (non Javadoc) 
	 * @author: caishuangxi
	 * @date: 2016年4月9日 上午8:26:20
	 * @Title: insertLog
	 * @Description: TODO
	 * @param log
	 * @return 
	 * @see cn.service.ApiService#insertLog(cn.domain.Log) 
	 */
	@Override
	public int insertLog(Log log) {
		// TODO Auto-generated method stub  
		return logMapper.insert(log);
	}

}
